package com.kygeng.springframework.core.io;

import cn.hutool.core.lang.Assert;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Title: DefaultResourceLoader
 * @Author: kygeng
 * @Package: com.kygeng.springframework.beans.core.io
 * @Date: 2024/7/21 20:30
 * @Description: 获取资源的实现类
 */
public class DefaultResourceLoader implements ResourceLoader {

    String CLASSPATH_URL_PREFIX = "classpath:";

    /**
     * 获取资源
     *
     * @param location
     * @return
     */
    @Override
    public Resource getResource(String location) {

        Assert.notNull(location, "location must not be null");

        //根据classPath加载资源
        if (location.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
        } else {
            try {
                //尝试当成url来处理
                URL url = new URL(location);
                return new UrlResource(url);
            } catch (MalformedURLException e) {
                //从文件加载资源
                return new FileSystemResource(location);
            }
        }
    }
}
